<body>
  <div style="margin:20px auto; text-align:center;">签名版</div>
  <canvas id="canvasbox" width="1000px" height="300px"
    style="border:1px solid green; display:block;"></canvas>
  <div class="btn" style="margin:0 auto; text-align:center;">
    <button id="savebtn">保存</button>
    <button id="clearbtn">清空</button>
  </div>
  <script>
    var canvasbox = document.getElementById("canvasbox");
    var ctx = canvasbox.getContext("2d");
    var iscanvas = false;
    var offsetX = '';
    var offsetY = '';
    canvasbox.addEventListener("touchstart", function (e) {
      iscanvas = true;
      let touch = e.touches[0]
      offsetX = touch.clientX;
      offsetY = touch.clientY;
    })
    canvasbox.addEventListener("touchmove", function (e) {
      if (iscanvas) {
        ctx.beginPath();
        let touch = e.touches[0]
        ctx.moveTo(offsetX, offsetY)
        ctx.lineTo(touch.clientX, touch.clientY)
        ctx.lineWidth = 5;
        ctx.stroke()
        offsetX = touch.clientX;
        offsetY = touch.clientY;
      }
    })
    canvasbox.addEventListener("touchend", function () {
      iscanvas = false;
    })
    canvasbox.addEventListener("touchcancel", function () {
      iscanvas = false;
    })
    var clearbtn = document.getElementById("clearbtn");
    clearbtn.addEventListener("click", function () {
      ctx.clearRect(0, 0, canvasbox.width, canvasbox.height)
    })
    var savebtn = document.getElementById("savebtn");
    savebtn.addEventListener("click", function () {
      downLoad(saveAsPNG(canvasbox));
    })
 
    function downLoad(url) {
      var oA = document.createElement("a");
      oA.download = 'download';// 设置下载的文件名，默认是'download'
      oA.href = url;
      document.body.appendChild(oA);
      oA.click();
      oA.remove(); // 下载之后把创建的元素删除
    }
    // 保存成png格式的图片
    function saveAsPNG(canvas) {
      return canvas.toDataURL("image/png");  //将图片转换成base64编码
 
      // ajax提交
      var nameImg = canvas.toDataURL("image/png");
      $.ajax({
        url: "",
        type: "post",
        data: { "nameImg": nameImg },
        success: function (res) {
          if (res.status == 1) {
            window.location.href = ""
          }
        }
      })
 
    }
    // 保存成jpg格式的图片
    function saveAsJPG(canvas) {
      return canvas.toDataURL("image/jpeg");
    }
  </script>
 
</body>